package com.example.utils;

import cn.hutool.core.util.StrUtil;

import java.lang.invoke.MethodHandles;
import java.util.Base64;

public class HClassLoader {

    @FunctionalInterface
    public interface HiddenClassFunction<T> {
        T apply(Class<?> hiddenClass) throws Exception;
    }

    public static <T> T executeBase64(String base64, String packName, HiddenClassFunction<T> function) throws Exception {
        byte[] modifiedBytes = PackageRenamer.changePackage(Base64.getDecoder().decode(base64), StrUtil.isNotBlank(packName) ? packName : "cn.ey.dp.rule.common.util");
        MethodHandles.Lookup lookup = MethodHandles.lookup();
        Class<?> hiddenClass = lookup.defineHiddenClass(modifiedBytes, true).lookupClass();
        Thread.currentThread().setContextClassLoader(hiddenClass.getClassLoader());
        return function.apply(hiddenClass);
    }


}